﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SpringStudio.Common;
using Sdepci.InfoCode.BLL.Authority;

namespace Sdepci.InfoCode.Web
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                // 如果当前登录计算机的用户是否是SDEPCI域的域用户，则直接登录
                string[] strs = this.Page.User.Identity.Name.Split('\\');
                if (strs[0].ToLower() == "sdepci" && new UserManager().Exist(strs[1].ToLower()))
                {
                    Session.Add("User", new User(strs[1].ToLower()));
                    this.Response.Redirect("Index.aspx");
                }

                // 将已输入的用户名赋值给输入框
                if (this.Request.QueryString["UserName"] != null && this.Request.QueryString["UserName"].Trim().Length > 0)
                {
                    this.txtUserName.Value = this.Request.QueryString["UserName"].Trim();
                }
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            bool result = false;

            if (this.txtUserName.Value.Trim() == "demo") // 实现测试用户的登录过程（实际部署时去掉）
            {
                if (this.txtPassword.Value == "123456")
                {
                    Session.Add("User", new User(this.txtUserName.Value, "测试用户", "u_deom", "山东院", "", new RoleManager().GetDefaultRole().RoleGuid));
                    this.Response.Redirect("Index.aspx");
                    result = true;
                }
            }
            else // 实现域用户的登录过程
            {
                if (new UserManager().IsAuthenticated(this.txtUserName.Value.Trim(), this.txtPassword.Value))
                {
                    Session.Add("User", new User(this.txtUserName.Value.Trim()));
                    this.Response.Redirect("Index.aspx");
                    result = true;
                }
            }

            if(!result)
            {
                this.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "<script language=\"javascript\">alert(\"登录失败：用户名或密码错误！\");document.location.href=\"Login.aspx?UserName=" + this.txtUserName.Value.Trim() + "\";</script>");
            }
        }
    }
}
